package com.sumer.psychology.blog.infrastructure.persistence.hibernate;

import com.sumer.psychology.blog.domain.model.*;
import com.sumer.psychology.common.persistence.hibernate.AbstractHibernateRepository;
import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * blog持久化
 * <p/>
 * Created by zhu on 14-8-14.
 */
public class HibernateBlogRepository extends AbstractHibernateRepository implements BlogRepository {
    @Override
    public void add(Blog aBlog) {
        session().saveOrUpdate(aBlog);
    }

    @Override
    public Blog blogOfId(BlogId id, BlogAvailability... availabilities) {
        Criteria criteria = session().createCriteria(Blog.class);
        criteria.add(Restrictions.eq("blogId", id));

        if (ArrayUtils.isNotEmpty(availabilities)) {
            List<SimpleExpression> availableExpressions = new ArrayList<>(availabilities.length);

            for (BlogAvailability availability : availabilities) {
                availableExpressions.add(
                        Restrictions.eq("availability", availability));
            }
            criteria.add(Restrictions.or(
                    availableExpressions.toArray(
                            new SimpleExpression[availableExpressions.size()])));
        }

        return (Blog) criteria.uniqueResult();
    }

    @Override
    public BlogId nextIdentity() {
        return new BlogId(UUID.randomUUID().toString());
    }

}
